package cn.itsource.hrm.service.impl;

import cn.itsource.hrm.domain.Course;
import cn.itsource.hrm.domain.CourseDetail;
import cn.itsource.hrm.domain.CourseMarket;
import cn.itsource.hrm.domain.dto.LoginUserInfo;
import cn.itsource.hrm.dto.CourseDTO;
import cn.itsource.hrm.dto.EmailMessageDTO;
import cn.itsource.hrm.dto.SMSMessageDTO;
import cn.itsource.hrm.exception.ErrorCode;
import cn.itsource.hrm.exception.GlobalException;
import cn.itsource.hrm.feign.client.CourseDocClient;
import cn.itsource.hrm.mapper.CourseDetailMapper;
import cn.itsource.hrm.mapper.CourseMapper;
import cn.itsource.hrm.mapper.CourseMarketMapper;
import cn.itsource.hrm.mapper.CourseTypeMapper;
import cn.itsource.hrm.service.ICourseService;
import cn.itsource.hrm.to.CourseDocTO;
import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.util.AssertUtils;
import cn.itsource.hrm.utils.UserContextHolder;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static cn.itsource.hrm.constant.MQConstant.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kai
 * @since 2021-01-18
 */
@Service
@Transactional
@Slf4j
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private CourseMarketMapper marketMapper;

    @Autowired
    private CourseDetailMapper detailMapper;

    @Autowired
    private CourseTypeMapper typeMapper;

    @Autowired
    private CourseDocClient client;  //feign的接口，调用发布的方法

    @Autowired
    private RabbitTemplate template;

    @Override
    public void saveCourseDTO(CourseDTO dto) {
        Course course = dto.getCourse();
        CourseDetail courseDetail = dto.getCourseDetail();
        CourseMarket courseMarket = dto.getCourseMarket();


        //1.参数校验
        //2.是否重复
            // 课程名不可重复
        AssertUtils.isTrue("课程名不可重复",!baseMapper.isExistCourseName(course.getName()));
        //3.先保存课程
        course.setStatus(0);

        LoginUserInfo userInfo = UserContextHolder.get();

        course.setTenantId(userInfo.getTenantId());
        course.setTenantName(userInfo.getTenantName());
        course.setUserId(userInfo.getUserid());
        course.setUserName(userInfo.getUserName());
        baseMapper.insert(course);

        //4.在保持课程营销
        courseMarket.setId(course.getId());
        marketMapper.insert(courseMarket);
        //5.保存课程详情;
        courseDetail.setId(course.getId());
        detailMapper.insert(courseDetail);

        // 6.保存的课程所在分类下的课程数量+1
        typeMapper.updateTotalCount(course.getCourseTypeId());

    }

    @Override

    public void onLineCourse(Long id) {

        LoginUserInfo userInfo = UserContextHolder.get();
        log.info("用户的信息： {}",userInfo);

        // 1. 判断id是否为空
        AssertUtils.isnotNull(ErrorCode.COURSE_ID_NOT_EMPTY_104.getMsg(),id);
        // 2. 如果不为空，查询课程信息
        Course course = baseMapper.selectById(id);
        AssertUtils.isnotNull(ErrorCode.COURSE_NOT_EMPTY_105.getMsg(),course);
        // 3. 判断课程是否已经上线
        Integer status = course.getStatus();
        AssertUtils.isEquals("课程已经上架",status,Course.ONLINE);
        // 4. 如果没有上线，先修改数据的状态
        course.setStatus(Course.ONLINE);

        baseMapper.updateById(course);
        // 5. 封装Docment对象
        CourseDocTO courseDocTO = course2Document(course);
        // 6. 调用search 服务的feign实现课程的发布;
        AjaxResult ajaxResult = client.onLineCourse(courseDocTO);
        if(!ajaxResult.isSuccess()){
            log.error("CourseServiceImpl, "+ajaxResult.getMessage());
            throw new GlobalException("课程上线失败");
        }
        //发布第三方的消息到消息队列
        sendMQ(course);
        log.info("消息发送完成====================");

    }

    private void sendMQ(Course course) {
        //有 电话号码/邮箱地址/用户id， 发送的消息的内容
        //7. 发送短信
        String content = "尊敬的用户，你关注的%s的机构，发布新的课程%s," +
                "点击：<a href='https://www.baidu.com/id=%s'/>";
        content = String.format(content, course.getTenantName(), course.getName(), course.getId());
        List<String> phones = Arrays.asList(new String[]{"1389999666", "15988887777"});
        SMSMessageDTO smsMessageDTO = new SMSMessageDTO(phones, content);
        template.convertAndSend(EXCHANGE_DIRECT_INFORM
                , SMS_ROUTING_KEY
                , smsMessageDTO);
        //8. 发送邮件
        List<String> emails = Arrays.asList(new String[]{"1389999666@qq.com", "15988887777@qq.com"});
        EmailMessageDTO emailMessageDTO = new EmailMessageDTO(emails, content);
        template.convertAndSend(EXCHANGE_DIRECT_INFORM
                , EMAIL_ROUTING_KEY
                , emailMessageDTO);
    }

    public CourseDocTO course2Document(Course course){

        CourseDocTO courseDocTO = new CourseDocTO();
        //查询营销的数据
        CourseMarket market = marketMapper.selectById(course.getId());
        //查询课程的详情
        CourseDetail detail = detailMapper.selectById(course.getId());

        BeanUtils.copyProperties(course,courseDocTO);
        BeanUtils.copyProperties(market,courseDocTO);
        BeanUtils.copyProperties(detail,courseDocTO);
        courseDocTO.setOnLineDate(new Date());
        courseDocTO.setSearchFiled(courseDocTO.getName()+" "+courseDocTO.getTenantName()+" "+courseDocTO.getDescription());

        return courseDocTO;
    }
}
